$(window).on("load", function () {
	$('#preloader').fadeOut('slow', function () {
		$(this).remove();
	});
});


$(function () {

	$('.more a').click(function () {
		$(this).html('加载中...')
		$(this).addClass('is-disabled')
	})
	//banner轮播 
	var picswiper = new Swiper('.banner-swiper', {
		loop: true,
		autoplay: {
			delay: 5000,
			disableOnInteraction: false,
		},
		navigation: {
			nextEl: '.banner-swiper .swiper-button-next',
			prevEl: '.banner-swiper .swiper-button-prev',
		},
		//分页器
		pagination: {
			el: '.banner-swiper .swiper-pagination',
			clickable: true,
		},
		initialSlide: 0, //初始化为第一张图
		observer: true, //修改swiper自己或子元素时，自动初始化swiper
		observeParents: true,
	});

	//banner轮播 
	var dSswiper = new Swiper('.d-swiper', {
		loop: true,
		autoplay: {
			delay: 5000,
		},
		// navigation: {
		// 	nextEl: '.d-swiper .swiper-button-next',
		// 	prevEl: '.d-swiper .swiper-button-prev',
		// },
		//分页器
		pagination: {
			el: '.d-swiper .swiper-pagination',
			// clickable: true,
			type: 'custom',
			renderCustom: function (swiper, current, total) {
				var temp = '<div class="d-swiper-pagination"><span>' + current + ' / ' + total + '</span></div>'
				return temp;
			}
		},
		initialSlide: 0, //初始化为第一张图
		observer: true, //修改swiper自己或子元素时，自动初始化swiper
		observeParents: true,
	});

	//其他选择 只能输入数字
	$(".other").find('input').keyup(function () {
		if (/[^\0-9,.]/.test($(this).val())) {
			$(this).val('');
		}
	})
	//跳转到内容页
	$('.js-list').on('click', '.js-jump', function () {
		var _id = $(this).attr('data-id');
		window.location.href = "details.html?id=" + _id;
	})

	//abroad跳转到内容页
	$('.js-list').on('click', '.js-jump-abroad', function () {
		var _id = $(this).attr('data-id');
		window.location.href = "abroad-details.html?id=" + _id;
	})

	//加号事件
	$('.js-list').on('click', '.js-jia', function () {
		var _id = $(this).attr('data-id');
	})

	//排序
	$('.js-sort').find('a').click(function () {
		var key = $(this).attr('id');
		var order = '1'; //0升序 1降序
		$('.js-sort').find('a').removeClass('active');
		$('.sort-updown').find('i').removeClass('select');
		$(this).addClass('active');
		if (key === 'profit' || key === 'amount') {

			$(this).attr('data-ord') == 0 ? $(this).attr('data-ord', "1") : $(this).attr('data-ord', "0")
			order = $(this).attr('data-ord');
			$(this).find('.sort-updown').find('i').eq(order).addClass('select');
			if (key === 'profit') {
				$('#amount').attr('data-ord', '1');
			} else {
				$('#profit').attr('data-ord', '1');
			}


		} else {
			$('#profit').attr('data-ord', '1');
			$('#amount').attr('data-ord', '1');

		}
		myList.sort(key, order)

	})




	setTimeout(function () {
		$('#preloader').fadeOut('slow', function () {
			$(this).remove();
		});
	}, 1000);




	//点击菜单
	$('.my-nav').find('a').each(function () {
		var href = $(this).attr("href");
		if (href == window.location.href.indexOf(href) > -1 || document.location.href.search(href) >= 0) {
			$(this).parent().addClass('active');
		}
	});

	//弹窗

	function getQueryString(paramKey) {
		var reg = new RegExp("(^|&)" + paramKey + "=([^&]*)(&|$)");
		var paramValue = window.location.search.substr(1).match(reg);
		if (paramValue != null) return paramValue[2];
		return '';
	}



})

//提示框
function Mypop(tit, html,btnOpts) {
	var initBtnOpts = {
		cancelBtnTxt: "关闭", //取消按钮文字
		//confirmBtnTxt:"确定",//确定按钮文字
		callback:function(){} //确定点击后的时间
	};
	btnOpts=$.extend(true, initBtnOpts, btnOpts);
	$(".my_pop").remove();
	$(".my_pop").off("click", ".close");
	$(".my_pop").off("click", ".close");
	var modalDiv =
		'<div class="my_pop">\
	  <div class="cover"></div>\
	  <div class="pop_box">\
	  <div class="pop_head"><button type="button" class="close">×</button><h4>' +
		tit +
		'</h4></div>\
	  <div class="pop_body" style="">' + html + '</div><div class="pop_foot"><div class="btncon">';
	  for(var k in btnOpts){
		  if(typeof btnOpts[k]=='string'){
			modalDiv +='<a href="javascript:;" data-type="'+k+'" class="btn">'+btnOpts[k]+'</a>';
		  }
		  
	  }
	  modalDiv +='</div></div></div></div>';
	$("body").append(modalDiv);
	$(".pop_box").find('[data-type=cancelBtnTxt]').addClass('close');
	var l=$(".pop_box").find('.btn').length;
	if(l==1){
		$(".pop_box").find('.btn').addClass('btn-main');
	}else{
		$(".pop_box").find('[data-type=cancelBtnTxt]').addClass('btn-o-grey');
		$(".pop_box").find('[data-type=confirmBtnTxt]').addClass('btn-main');
	}
	var ww = $(window).width();
	var popleft = ww / 2 - 300;
	if (ww > 750) {
		$(".my_pop").find(".pop_box").css({
			width: '600px',
			left: popleft + 'px'
		});
	}
	ww > 750 ? (ww = 750) : (ww = ww);
	$(".pop_box").addClass("animation-dialogue-in"); //弹出层后，禁用body和html滚动
	/* $("body,html").addClass("forbid-scroll"); */
	$(".my_pop").on("click", ".close", function () {
		$(this)
			.parents(".my_pop")
			.hide();
		$(".pop_box").removeClass("animation-dialogue-in");
		/* $("body,html").removeClass("forbid-scroll"); */
	});
	$(".my_pop").on("click", "[data-type=confirmBtnTxt]", function () {
		if(btnOpts.hasOwnProperty('callback')){
			btnOpts.callback();
		}
		
	});
}
Mypop.prototype.hide=function(){
$(".my_pop").hide();
$(".pop_box").removeClass("animation-dialogue-in");	
}
//跟隨提示框
function Followpop(tit, html,pos) {
	$(".f_pop").remove();
	var modalDiv =
		'<div class="f_pop">\
	  <div class="f_pop_box">\
	  <div class="f_pop_head"><h4>' +
		tit +
		'</h4></div>\
	  <div class="f_pop_body" style="">' + html + '</div>';
	  modalDiv +='</div></div>';
	$("body").append(modalDiv);


		$(".f_pop").find(".f_pop_box").css({
			width: '400px',
			left: pos.x + 'px',
			top: pos.y + 'px'
		});
	$(".f_pop_box").show(); //弹出层后，禁用body和html滚动
}
Followpop.prototype.hide=function(){
	$(".f_pop").remove();
}
var myList = {
	node: null,
	flag: 0, //0pc 1mob
	data: [],
	temp:"default",
	render: function (obj) {
		this.node = $(obj.node);
		this.data = obj.data;
        if(obj.temp){
			this.temp=obj.temp;
		}
		
		if(this.temp=='default'){
			this.renderTemp(obj.data);
			return;
		}
		if(this.temp==='abroad'){
			console.log(this.temp);
			this.renderAbroad(obj.data);
		}
		
	},
	renderTemp: function (d) {
		var _that = this;
		var html = '<div class="swiper-wrapper">'
		for (var i = 0; i < d.length; i++) {
			html += '<div class="swiper-slide" data-id="' + d[i].id + '">\
			 <div class="swiper-item-con">\
				 <a class="js-jump" data-id="' + d[i].id + '" href="javascript:;">\
					 <div class="live-wrap">\
						 <div class="live-body"><img src="' + d[i].imgSrc + '" alt=""></div>\
 				     </div>\
					 <div class="live-tit">' + d[i].name + '</div>\
					 <div class="live-price"><span class="js-price" data-val="' + d[i].amount + '"></span><span class="live-sold">已售<em class="js-sold" data-val="' + d[i].sold + '"></em></span></div>\
				</a>\
				 <a class="live-shop flex align-center" target="_blank" href="' + d[i].shopLink + '">\
					 <i class="iconfont icon-shandian gutter-pr-6"></i><span class="live-shop-name">' + d[i].shopName + '</span>\
				 </a>\
				 <div class="live-star js-star" data-val="' + d[i].shopScore + '"></div>\
				 <div class="live-zhuan flex align-center justify-between">\
					 <span class="js-zhuan" data-val="' + d[i].profit + '"></span>\
					 <div class="flex align-center"><i class="iconfont icon-jiahao js-jia" data-id="' + d[i].id + '"></i>'
					 if(d[i].hasOwnProperty('button')){
						html+='<a class="btn btn-o-mini" style="margin-left:5px;" data-id="'+d[i].button.id+'">'+d[i].button.name+'</a>'
					 }
					
				html+='</div></div></div></div>'
			
		}
		html += '</div>';
		this.node.empty().append(html);
		//价格格式化
		this.node.find('.js-zhuan').each(function () {
			var val = $(this).attr('data-val');
			var res = _that.fomatPrice(val);
			var temp = '赚&nbsp;$<span class="format"><em>' + res[0] + '</em>.' + res[1] + '</span>'
			$(this).html(temp);
		})

		this.node.find('.js-star').each(function () {
			var val = $(this).attr('data-val');
			var starTemp = _that.showStar(val);
			$(this).html(starTemp);
		})
		this.node.find('.js-price').each(function () {
			var val = $(this).attr('data-val');
			var res = _that.fomatPrice(val);
			var temp = '$' + res[0] + '.' + res[1];
			$(this).html(temp);
		})
		this.node.find('.js-sold').each(function () {
			var val = $(this).attr('data-val');
			var res = _that.formatSold(val);
			$(this).html(res);
		})

	},
	renderAbroad: function (d) {
		var _that = this;
		var html = '<div class="swiper-wrapper">'
		for (var i = 0; i < d.length; i++) {
			html += '<div class="swiper-slide" data-id="' + d[i].id + '">\
			 <div class="swiper-item-con">\
				 <a class="js-jump-abroad" data-id="' + d[i].id + '" href="javascript:;">\
					 <div class="live-wrap">\
						 <div class="live-body"><img src="' + d[i].imgSrc + '" alt=""></div>\
 				     </div>\
					 <div class="live-tit">' + d[i].name + '</div>\
					 </a>\
				<div>\
				<div class="abroad-price live-zhuan"> <span class="js-lowprice danger-color-txt" data-val="' + d[i].lowprice + '"></span> - <span class="js-lowprice danger-color-txt gutter-pr-6" data-val="' + d[i].highprice + '"></span><span class="oprice">$' + d[i].oprice + '</span></div>\
				 <div class="abroad-off flex align-center">\
					 <i class="iconfont icon-zhekou1 gutter-pr-6"></i><span class="abroad-off-txt gutter-pr-6">' + d[i].off + ' off</span>\
					 <span class="btncon"><a class="btn btn-o-mini btn-off js-sprice"  data-id="'+d[i].id +'">查看折扣</a></span>\
				 </div>\
				 </div>\
				 <div class="live-star js-star" data-val="' + d[i].shopScore + '"></div>\
				 <div class="live-zhuan flex align-center justify-end">\
					 <div class="flex align-center"><i class="iconfont icon-jiahao js-jia" data-id="' + d[i].id + '"></i>'
					 if(d[i].hasOwnProperty('button')){
						html+='<a class="btn btn-o-mini" style="margin-left:5px;" data-id="'+d[i].button.id+'">'+d[i].button.name+'</a>'
					 }
					
				html+='</div></div></div></div>'
			
		}
		html += '</div>';
		this.node.empty().append(html);
		//价格格式化
		this.node.find('.js-lowprice').each(function () {
			var val = $(this).attr('data-val');
			var res = _that.fomatPrice(val);
			var temp = '$<span class="format"><em>' + res[0] + '</em>.' + res[1] + '</span>'
			$(this).html(temp);
		})

		this.node.find('.js-star').each(function () {
			var val = $(this).attr('data-val');
			var starTemp = _that.showStar(val);
			$(this).html(starTemp);
		})
		this.node.find('.js-price').each(function () {
			var val = $(this).attr('data-val');
			var res = _that.fomatPrice(val);
			var temp = '$' + res[0] + '.' + res[1];
			$(this).html(temp);
		})
		function render_tab(_id){
			var _item=null;
			for(var i=0;i<d.length;i++){
				if(d[i].id==_id){
				  _item=d[i].stepPrice;
				  break;
				}
			}
			var temp='<div class="live-table"><table cellspacing="0" cellpadding="0" border="0">\
			<thead><tr><th class="table-cell"><div class="cell">采購數量</div></th><th class="table-cell"><div class="cell">單盒價格</div></th><th class="table-cell"><div class="cell">折扣(市場價格)</div></th></tr></thead>\
			<tbody>';
		   for(var j=0;j<_item.length;j++){
			var _color='color'+j;
			if(j>=4){
				_color="color4"
			}
			temp+='<tr class="'+_color+'"><td class="table-cell"><div class="cell">'+_item[j].nums+'</div></td><td class="table-cell"><div class="cell">'+_item[j].price+'</div></td><td class="table-cell"><div class="cell">'+_item[j].off+' off</div></td></tr>'
		   }
			temp+='</tbody>\
			</table></div>'
			return {tpl:temp,len:_item.length};
		}
		if($(window).width()>=750){
			var f_pop=null;
			this.node.find('.js-sprice').hover(function(e){
				var _id = $(this).attr('data-id');
		
				var f_temp=render_tab(_id);
				var _x=e.clientX-200;
				if(_x<0){
					_x=0;
				}
				if(_x>$(window).width()-400){
					_x=$(window).width()-400;
				}
				var _y=e.clientY-130-36*f_temp.len;
			   
				console.log(_y);
				f_pop=new Followpop("梯度價格", f_temp.tpl,{x:_x,y:_y});
			},function(e){
				f_pop.hide();
			})
		}
		
		if($(window).width()<750){
			this.node.find(".js-sprice").click(function(){
				var _id = $(this).attr('data-id');
				var p_temp=render_tab(_id);
				Mypop("梯度價格", p_temp.tpl);
			}) 				
			
		}
	



	},
	formatSold: function (v) {
		var num = '0';
		v = parseInt(v);
		if (v >= 10000) {
			var cv = parseInt(v / 10000);
			num = cv + '萬+';

		} else {
			num = v;
		}

		return num;

	},
	showStar: function (v) {
		if (v > 5) {
			v = 5;
		}
		v = parseFloat(v).toFixed(1);
		var html = '';
		var cv = v.toString().split(".");
		var fn = Number(cv[0]);
		var hn = Number(cv[1]); //半星值
		for (var i = 0; i < 5; i++) {
			if (i < fn) {
				html += '<span><img src="./images/star.png"></span>';
			} else {
				if (i == fn) {
					if (hn < 3) {
						html += '<span><img src="./images/star-o.png"></span>';
					} else if (hn >= 3 && hn < 8) {
						html += '<span><img src="./images/star-half.png"></span>';
					} else {
						html += '<span><img src="./images/star.png"></span>';
					}
					continue;

				} else {
					html += '<span><img src="./images/star-o.png"></span>';
				}
			}
		}
		html += '<em class="score">' + v + '</em>'
		return html

	},
	fomatPrice: function (v) {
		/*原来用的是Number(value).toFixed(0)，这样取整时有问题，例如0.51取整之后为1，感谢Nils指正*/
		var decimal = '00';
		var integer = '0';
		var cv = parseFloat(v).toFixed(2)
		var intPart = Number(cv) | 0; //获取整数部分
		var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); //将整数部分逢三一断
		var floatPart = "00"; //预定义小数部分
		var value2Array = cv.toString().split(".");
		var isNegtiveNo = ''

		// if (intPartFormat == 0) {

		// 	if (v.toString().indexOf('-') != 1) isNegtiveNo = '-' //修复小于0负数丢失的问题

		// }

		//=2表示数据有小数位

		if (value2Array.length == 2) {

			floatPart = value2Array[1].toString(); //拿到小数部分

			if (floatPart.length == 1) { //补0,实际上用不着
				decimal = floatPart + '0';
				integer = isNegtiveNo + intPartFormat;
			} else {
				decimal = floatPart;
				integer = isNegtiveNo + intPartFormat;
			}

		} else {
			decimal = floatPart;
			integer = isNegtiveNo + intPartFormat;

		}
		return [integer, decimal]
	},
	sort: function (key, order) {
		var _that = this;
		var nd = JSON.parse(JSON.stringify(this.data))
		if (key == 'recommend') {
			this.renderTemp(this.data);
		} else {
			var sortData = nd.sort(_that.compareValues(key, order));
			this.renderTemp(sortData);
		}


		//0升序 1降序

	},
	compareValues: function (key, order) {
		return function innerSort(a, b) {
			if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
				return 0;
			}
			var varA = parseFloat(a[key]);
			var varB = parseFloat(b[key]);
			let comparison = 0;
			if (varA > varB) {
				comparison = 1;
			} else if (varA < varB) {
				comparison = -1;
			}
			return (
				(order == '1') ? (comparison * -1) : comparison
			);
		};
	}
}